﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using System.Collections.Generic;

/// <summary>
/// Utils 的摘要说明
/// </summary>
public class Utils
{
	public Utils()
	{
		//
		// TODO: 在此处添加构造函数逻辑
		//



       
	}
    /// <summary>
    /// 过滤掉关键的字符，减少Sql注入攻击
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string SafeSqlStr(string str) 
    {
        return str.Replace("'", " ‘")
            .Replace("--", "- -")
            .Replace("/*", "、 *")
            .Replace("*/", "、 *");
    }

    /// <summary>
    /// 将GUID样式的字符串转换成GUID。
    /// 如果给定的为NULL或空字符串，则会返回DBNull.Value
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static object StrToGuid(string value)
    {
        if (value == null || value.Trim() == string.Empty)
            return DBNull.Value;
        return new Guid(value.Trim());
    }
    /// <summary>
    /// 将GUID样式的字符串转换成GUID。
    /// 如果给定的为NULL或空字符串，则会返回Guid.Empty
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static Guid TryToGuid(string value)
    {
        if (value == null || value.Trim() == string.Empty)
            return Guid.Empty;
        try
        {
            Guid g = new Guid(value);
            return g;
        }
        catch
        {
            return Guid.Empty;
        }
    }
    /// <summary>
    /// 显示消息
    /// </summary>
    /// <param name="lblMsg"></param>
    /// <param name="msg"></param>
    /// <param name="args"></param>
    public static void ShowMsg(Label lblMsg, string msg, params object[] args)
    {
        if (lblMsg == null) return;

        if (lblMsg.Text == "")
        {
            if (args == null || args.Length == 0)
                lblMsg.Text = msg;
            else lblMsg.Text = string.Format(msg, args);
        }
        else
        {
            if (args == null || args.Length == 0)
                lblMsg.Text += "<br/>" + msg;
            else lblMsg.Text += "<br/>" + string.Format(msg, args);
        }
        if (msg == "")
            lblMsg.Visible = false;
        else if (!lblMsg.Visible) 
            lblMsg.Visible = true;
    }
    /// <summary>
    /// 显示消息。
    /// Example：Utils.ShowMsgAnthem(MsgCtrl, "Hello");
    /// 带参数的：Utils.ShowMsgAnthem(MsgCtrl, "Hello, {0},{1}", "rainbow", "lai");
    /// 如果参数msg为""，则清除消息。
    /// </summary>
    /// <param name="lblMsg"></param>
    /// <param name="msg"></param>
    /// <param name="args"></param>
    public static void ShowMsgAnthem(Anthem.Label lblMsg, string msg, params object[] args)
    {
        if (lblMsg == null) return;

        if (msg == "")
        {
            lblMsg.Text = "";
            lblMsg.Visible = false;
            lblMsg.AutoUpdateAfterCallBack = true;
            return;
        }
        else if (!lblMsg.Visible)
        {
            lblMsg.Visible = true;
        }

        if (lblMsg.Text == "")
        {
            if (args == null || args.Length == 0)
                lblMsg.Text = msg;
            else lblMsg.Text = string.Format(msg, args);
        }
        else
        {
            if (args == null || args.Length == 0)
                lblMsg.Text += "<br/>" + msg;
            else lblMsg.Text += "<br/>" + string.Format(msg, args);
        }
        
        lblMsg.UpdateAfterCallBack = true;
    }
    /// <summary>
    /// 隐藏消息框
    /// </summary>
    /// <param name="lblMsg"></param>
    public static void HideMsgAnthem(Anthem.Label lblMsg)
    {
        ShowMsgAnthem(lblMsg, "");
    }

    /// <summary>
    /// 新的消息显示方式
    /// </summary>
    /// <param name="lblMsg"></param>
    /// <param name="msg"></param>
    /// <param name="args"></param>
    public static void ShowMsgAnthemEx(Anthem.Label lblMsg, string msg, params object[] args)
    {
        if (lblMsg == null) return;

        if (msg == "")
        {
            lblMsg.Text = "";
            lblMsg.Visible = false;
            lblMsg.AutoUpdateAfterCallBack = true;
            return;
        }
        else if (!lblMsg.Visible)
        {
            lblMsg.Visible = true;
        }

        bool isFirstText = lblMsg.Text == "";
        if (isFirstText)
        {
            lblMsg.Text = "<div id=\"msg_err\" class=\"msg_err\">"
                + "<div id=\"maindd_err\" class=\"maindd_err\"><img src=\""
                + Globals.HttpRoot
                + "images/er01.gif\" alt=\"tl\" class=\"msg_tl\" /><img src=\""
                + Globals.HttpRoot
                + "images/er02.gif\" alt=\"tr\" class=\"msg_tr\" /><img src=\""
                + Globals.HttpRoot
                + "images/er03.gif\" alt=\"bl\" class=\"msg_bl\" /><img src=\""
                + Globals.HttpRoot
                + "images/er04.gif\" alt=\"br\" class=\"msg_br\" /><img src=\""
                + Globals.HttpRoot
                + "images/csts.gif\" alt=\"cs\" class=\"msg_csts\"  onClick=\"cserr()\"/> "
                + "<div class=\"content_err\">";

            if (args == null || args.Length == 0)
                lblMsg.Text += msg;
            else lblMsg.Text += string.Format(msg, args);
            lblMsg.Text += "<span width='0' />";
        }
        else
        {
            if (args == null || args.Length == 0)
                lblMsg.Text = lblMsg.Text.Replace("<span width='0' />", "<br/>" + msg + "<span width='0' />");
            else 
                lblMsg.Text = lblMsg.Text.Replace("<span width='0' />", "<br/>" + string.Format(msg, args) + "<span width='0' />");
        }
        if(isFirstText)
            lblMsg.Text += "</div> </div> </div>";
        lblMsg.AutoUpdateAfterCallBack = true;
    }






    /// <summary>
    /// 对当前的Gridview，选择下一条记录。如果已经选择了最后一条，则不会变动。
    /// callbackMethod: 为给定需要调用的方法，如果为Null则不会调用这个方法。
    /// </summary>
    /// <param name="gv"></param>
    /// <param name="callbackMethod"></param>
    public static void SelectNextRecord(GridView gv, GridViewCommandEventHandler callbackMethod)
    {
        if (gv == null || gv.Rows.Count == 0)
            return;

        if (gv.SelectedIndex == gv.Rows.Count - 1) 
            return;

        int nextIndex = gv.SelectedIndex + 1;
        if (nextIndex >= gv.Rows.Count - 1)
            nextIndex = gv.Rows.Count - 1;

        SelectRecord(gv, nextIndex, callbackMethod);
    }

    /// <summary>
    /// 当Gridview删除记录时，调用这个方法。
    /// 注意，调用的最佳时机为执行RowDeleting的最后。
    /// </summary>
    /// <param name="gv"></param>
    /// <param name="currentIndex"></param>
    /// <param name="callbackMethod"></param>
    public static void SelectNextAfterDelete(GridView gv, int currentIndex, GridViewCommandEventHandler callbackMethod)
    {
        if (gv == null || gv.Rows.Count == 0)
            return;

        if (gv.SelectedIndex == gv.Rows.Count - 1)
            return;

        int nextIndex = currentIndex;
        if (nextIndex >= gv.Rows.Count - 1)
            nextIndex = gv.Rows.Count - 1;
        if (nextIndex == -1)
            nextIndex = 0;

        SelectRecord(gv, nextIndex, callbackMethod);
    }

    /// <summary>
    /// 选择Gridview的选中的记录。需要Girdview响应select的Command。
    /// </summary>
    /// <param name="gv"></param>
    /// <param name="currentIndex"></param>
    /// <param name="callbackMethod"></param>
    public static void SelectRecord(GridView gv, int currentIndex, GridViewCommandEventHandler callbackMethod)
    {
        if (currentIndex == -1 || currentIndex >= gv.Rows.Count)
            return;
        gv.SelectedIndex = currentIndex;
        GridViewCommandEventArgs ea = new GridViewCommandEventArgs(gv.Rows[currentIndex],
                    null, new CommandEventArgs("select", (object)currentIndex));
        if (callbackMethod != null)
            callbackMethod(gv, ea); 
    }
    /// <summary>
    /// select row of gridview, 需要指定commandName 
    /// </summary>
    /// <param name="gv"></param>
    /// <param name="currentIndex"></param>
    /// <param name="commandName"></param>
    /// <param name="callbackMethod"></param>
    public static void SelectRecord(GridView gv, int currentIndex, string commandName, GridViewCommandEventHandler callbackMethod)
    {
        if (currentIndex == -1 || currentIndex >= gv.Rows.Count)
            return;
        gv.SelectedIndex = currentIndex;
        GridViewCommandEventArgs ea = new GridViewCommandEventArgs(gv.Rows[currentIndex],
                    null, new CommandEventArgs(commandName, (object)currentIndex));
        if (callbackMethod != null)
            callbackMethod(gv, ea); 
    }

    /// <summary>
    /// 判断字符串是否是NULL或者string.Empty
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    public static bool IsNullorEmpty(string text)
    {
        return text == null || text.Trim() == string.Empty;
    }

    /// <summary>
    /// 设置下列列表控件的SelectedValue
    /// </summary>
    /// <param name="control">DropDownList控件</param>
    /// <param name="strValue">SelectedValue的值</param>
    public static void SetDropDownListItem(DropDownList control, string strValue)
    {
        if (!IsNullorEmpty(strValue))
        {
            control.ClearSelection();
            ListItem item = control.Items.FindByValue(strValue);
            if (item != null)
            {
                control.SelectedValue = item.Value;
            }
        }
    }

    /// <summary>
    /// 判断输入的字符是否为数字
    /// </summary>
    /// <param name="strValue"></param>
    /// <returns></returns>
    public static bool IsNumerical(string strValue)
    {
        return Regex.IsMatch(strValue, @"^[0-9]*$");
    }

    /// <summary>
    /// 获取Html的锚点
    /// </summary>
    /// <param name="innerText"></param>
    /// <param name="href"></param>
    /// <returns></returns>
    public static HtmlAnchor GetHtmlAnchor(string innerText, string href)
    {
        HtmlAnchor htmlAnchor = new HtmlAnchor();
        htmlAnchor.InnerText = innerText;
        htmlAnchor.HRef = href;

        return htmlAnchor;
    }

    /// <summary>
    /// 定位到指定的页面
    /// </summary>
    /// <param name="GoPage">目标页面</param>
    public static void GoTo(string GoPage)
    {
        HttpContext.Current.Response.Redirect(GoPage);
    }

    /// <summary>
    /// 定位到指定的页面
    /// </summary>
    /// <param name="control">当前请求的page</param>
    /// <param name="page">目标页面</param>
    public static void Location(Control control, string page)
    {
        string js = "<script language='JavaScript'>";
        js += "top.location='" + page + "'";
        js += "</script>";
        control.Page.RegisterStartupScript("", js);
    }

    /**/
    /// <summary>
    /// 提示信息并定位到指定的页面
    /// </summary>
    /// <param name="control">当前请求的page</param>
    /// <param name="page">目标页面</param>
    /// <param name="message">提示信息</param>
    public static void AlertAndLocation(Control control, string page, string message)
    {
        string js = "<script language='JavaScript'>";
        js += "alert('" + message + "');";
        js += "top.location='" + page + "'";
        js += "</script>";
        control.Page.RegisterStartupScript("", js);
    }

    /**/
    /// <summary>
    /// 关闭页面，并返回指定的值
    /// </summary>
    /// <param name="control"></param>
    /// <param name="returnValue"></param>
    public static void CloseWin(Control control, string returnValue)
    {
        string js = "<script language='JavaScript'>";
        js += "window.parent.returnValue='" + returnValue + "';";
        js += "window.close();";
        js += "</script>";
        control.Page.RegisterStartupScript("", js);
    }

    /// <summary>
    /// 替换字符串的单引号
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static string EscapeSingleQuote(string input)
    {
        if (!string.IsNullOrEmpty(input))
        {
            return input.Replace("'", @"\'");
        }
        else
        {
            return input;
        }
    }

    public static string FormateDateTime(object value, bool showTime)
    {
        if (value == null || value == DBNull.Value)
        {
            return string.Empty;
        }

        DateTime dt = Convert.ToDateTime(value);
        if (dt == DateTime.MinValue || dt == DateTime.MaxValue)
        {
            return string.Empty;
        }
        else
        {
            return dt.ToString(showTime ? "yyyy-M-d H:m:s" : "yyyy-M-d");
        }
    }

    public static string DateTimeToString(DateTime dt)
    {
        return DateTimeToString(dt, false);
    }

    /// <summary>
    /// DateTime to string. Ignore max and min datetime value.
    /// </summary>
    /// <param name="dt"></param>
    /// <param name="showTime"></param>
    /// <returns></returns>
    public static string DateTimeToString(DateTime dt, bool showTime)
    {
        if (dt == DateTime.MinValue || dt == DateTime.MaxValue)
        {
            return string.Empty;
        }

        return dt.ToString(showTime ? "yyyy-MM-dd HH:mm:ss" : "yyyy-MM-dd");
    }

    public static bool ParseIntQueryString(HttpRequest Request, string key, ref int value)
    {
        return ParseIntQueryString(Request, key, false, ref value);
    }

    public static bool ParseIntQueryString(HttpRequest Request, string key, bool required, ref int value)
    {
        string svalue = Request.QueryString[key];
        if (!string.IsNullOrEmpty(svalue))
        {
            return int.TryParse(svalue, out value);
        }
        else
        {
            return !required;
        }
    }

    public static List<int> GetGridViewCheckItemIDs(GridView gv)
    {
        return GetGridViewCheckItemIDs(gv, "chk");
    }

    public static List<int> GetGridViewCheckItemIDs(GridView gv, string chkControlId)
    {
        List<int> ids = new List<int>();
        foreach (GridViewRow row in gv.Rows)
        {
            CheckBox chk = row.FindControl(chkControlId) as CheckBox;
            if (chk.Checked)
            {
                int id = Convert.ToInt32(gv.DataKeys[row.RowIndex].Value);
                ids.Add(id);
            }
        }

        return ids;
    }
}
